package com.daisuxia.web.controller;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import redis.clients.jedis.JedisCluster;

import com.daisuxia.back.test.SerializeUtil;
import com.daisuxia.back.utils.RequestUtils;
import com.daisuxia.constant.Constant;
import com.daisuxia.web.pojo.BackUser;
import com.daisuxia.web.pojo.ChannelInfo;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.service.IInfoIndexService;
import com.octo.captcha.service.image.ImageCaptchaService;

public class BaseController {

	public static final String MESSAGE = "message";
	public static final String LOGING_DEVICE_PREFIX = "device_";
	public static final int FRONT_USER_EXIST_TIME = 259200;// 3*24*60*60
	public static final int BACK_USER_EXIST_TIME = 259200;// 3*24*60*60

	private static Logger loger = Logger.getLogger(BaseController.class);

	@Autowired
	JedisCluster jedisCluster;
	@Autowired
	private IInfoIndexService infoIndexService;

	/**
	 * 得到 session
	 * 
	 * @return
	 */
	protected HttpSession getSession(HttpServletRequest request) {
		return request.getSession();
	}

	/**
	 * 获取IP地址
	 * 
	 * @param request
	 * @return
	 */
	public String getIpAddr(HttpServletRequest request) {
		return RequestUtils.getIpAddr(request);
	}

	@Autowired
	private ImageCaptchaService captchaService;

	/**
	 * 得到session中的admin user对象
	 */
	public BackUser loginAdminUser(HttpServletRequest request) {
		if (request == null) {
			request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		}
		BackUser backUser = (BackUser) request.getSession().getAttribute(Constant.BACK_USER);
		return backUser;
	}

	/**
	 * 得到session中的ChannelInfo对象
	 */
	public ChannelInfo loginChannelInfo(HttpServletRequest request) {
		byte[] channelInfo = jedisCluster.get((Constant.CHANNEL_INFO + request.getSession().getId()).getBytes());
		if (null == channelInfo) {
			return null;
		}
		ChannelInfo info = (ChannelInfo) SerializeUtil.unserialize(channelInfo);
		return info;
	}

	public User loginFrontUserByDeiceId(HttpServletRequest request) {
		String deviceId = request.getParameter("deviceId");
		loger.info("设备号deviceId=" + deviceId);
		if (StringUtils.isBlank(deviceId)) {
			return null;
		}
		byte[] userInfo = jedisCluster.get((LOGING_DEVICE_PREFIX + deviceId).getBytes());

		if (null == userInfo) {
			return null;
		}

		User zbUser = (User) SerializeUtil.unserialize(userInfo);

		loger.info("loginFrontUserByDeiceId key :" + (LOGING_DEVICE_PREFIX + deviceId).getBytes() + ",userId:" + zbUser.getId());
		return zbUser;
	}

	/**
	 * 验证码
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public boolean validateSubmit(HttpServletRequest request, HttpServletResponse response) {
		try {
			String key = request.getSession(false).getId();
			String value = jedisCluster.get(key);
			jedisCluster.del(key);
			return request.getParameter("captcha").toLowerCase().equals(value);
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 获得request中的参数
	 * 
	 * @param request
	 * @return string object类型的map
	 */
	public HashMap<String, Object> getParametersO(HttpServletRequest request) {
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		if (request == null) {
			request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		}
		Map req = request.getParameterMap();
		if ((req != null) && (!req.isEmpty())) {
			Map<String, Object> p = new HashMap<String, Object>();
			Collection keys = req.keySet();
			for (Iterator i = keys.iterator(); i.hasNext();) {
				String key = (String) i.next();
				Object value = req.get(key);
				Object v = null;
				if ((value.getClass().isArray()) && (((Object[]) value).length > 0)) {
					if (((Object[]) value).length > 1) {
						v = ((Object[]) value);
					} else {
						v = ((Object[]) value)[0];
					}
				} else {
					v = value;
				}
				if ((v != null) && ((v instanceof String)) && !"\"\"".equals(v)) {
					String s = ((String) v).trim();
					if (s.length() > 0) {
						p.put(key, s);
					}
				}
			}
			hashMap.putAll(p);
			// 读取cookie
			hashMap.putAll(ReadCookieMap(request));

		}
		return hashMap;
	}

	/**
	 * 得到页面传递的参数封装成map
	 */

	public Map<String, String> getParameters(HttpServletRequest request) {
		if (request == null) {
			request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		}
		Map<String, String> p = new HashMap<String, String>();
		Map req = request.getParameterMap();
		if ((req != null) && (!req.isEmpty())) {

			Collection keys = req.keySet();
			for (Iterator i = keys.iterator(); i.hasNext();) {
				String key = (String) i.next();
				Object value = req.get(key);
				Object v = null;
				if ((value.getClass().isArray()) && (((Object[]) value).length > 0)) {
					v = ((Object[]) value)[0];
				} else {
					v = value;
				}
				if ((v != null) && ((v instanceof String)) && !"\"\"".equals(v)) {
					String s = (String) v;
					if (s.length() > 0) {
						p.put(key, s);
					}
				}
			}
			// 读取cookie
			p.putAll(ReadCookieMap(request));
			return p;
		}
		return p;
	}

	/**
	 * 将cookie封装到Map里面
	 * 
	 * @param request
	 * @return
	 */
	private static Map<String, String> ReadCookieMap(HttpServletRequest request) {
		Map<String, String> cookieMap = new HashMap<String, String>();
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				cookieMap.put(cookie.getName(), cookie.getValue());
			}
		}
		return cookieMap;
	}

	/**
	 * @param key
	 * @param flag
	 * @return true:设置成功（代表是没有超发），false：设置失败（超发）
	 */
	public boolean checkForFront(String key, String flag) {
		loger.info("checkForFront key:" + key + ",flag:" + flag);
		String expireKey = key + flag;
		loger.info("checkForFront expireKey:" + expireKey);
		Long tooMuchFlag = jedisCluster.setnx(expireKey, "1");
		loger.info("checkForFront key:" + expireKey + ",result:" + tooMuchFlag);
		if (tooMuchFlag <= 0) {
			return false;
		}
		jedisCluster.expire(expireKey, 60);
		return true;
	}

	public boolean delCheckForFront(String key, String flag) {
		loger.info("delCheckForFront key:" + key + ",flag:" + flag);
		String expireKey = key + flag;
		loger.info("delCheckForFront expireKey:" + expireKey);
		jedisCluster.del(expireKey);
		return true;
	}

}
